﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using tomvangaever.library.WS;
using tomvangaever.library.XSLT;
using Microsoft.SharePoint;

namespace SPXsltWs.SPXsltWsWebpart
{
    public partial class SPXsltWsWebpartUserControl : UserControl
    {
        public SPXsltWsWebpart WebPart { get; set; }
        public string WebServiceUrl { get; set; }
        public string SoapAction { get; set; }
        public string SoapBody { get; set; }
        public string Xslt { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (WebPart != null)
                {
                    // Retrieve vars from Webpart
                    WebServiceUrl = WebPart.WebServiceUrl;
                    SoapAction = WebPart.SoapAction;
                    SoapBody = WebPart.SoapBody;
                    Xslt = WebPart.Xslt;

                    //Show properties link if values are empty
                    if (string.IsNullOrEmpty(WebServiceUrl) &&
                        string.IsNullOrEmpty(Xslt))
                    {
                        litoutput.Text = OpenToolPane();
                    }
                    else
                    {
                        if (WebServiceUrl.StartsWith("_vti_bin")) WebServiceUrl = string.Format("{0}/{1}", SPContext.Current.Web.Url, WebServiceUrl);
                        if (WebServiceUrl.StartsWith("/_vti_bin")) WebServiceUrl = string.Format("{0}{1}", SPContext.Current.Site.Url, WebServiceUrl);
                        string xml = WSHelper.Invoke(WebServiceUrl, SoapAction, SoapBody);
                        string data = XsltHelper.ApplyXSLTransformation(xml, Xslt);
                        litoutput.Text = data;
                    }
                }
            }
            catch (Exception ex)
            {
                string errorwrapper = "<div class='ms-error'>{0}</div>";
                litoutput.Text = string.Format(errorwrapper, ex.ToString());
            }
        }

        private string OpenToolPane()
        {
            string message = "<div>To add the webservice, soap and xslt specifications, {0} and click settings.</div>";
            return string.Format(message,"<a href=\"javascript:MSOTlPn_ShowToolPane2Wrapper('Edit', '129','" + this.WebPart.ID + "')\">open tool pane</a>");
        }

        private void AssertEmptySetting(string name, string value)
        {
            if (string.IsNullOrEmpty(value))
            {

                string message = "<b>{0}</b> has not been specified." + OpenToolPane();
                throw new ArgumentException(string.Format(message, name));
            }
        }
    }
}
